package com.qfedu.luck.service.impl;

import com.qfedu.luck.dao.LuckDao;
import com.qfedu.luck.dao.impl.LuckDaoImpl;
import com.qfedu.luck.entity.Luck;
import com.qfedu.luck.service.LuckService;
import com.qfedu.luck.vo.R;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Random;

/**
 * @program: LuckStudy
 * @description:
 * @author: Feri(邢朋辉)
 * @create: 2021-02-24 14:41
 */
public class LuckServiceImpl implements LuckService {

    private static LinkedHashMap<Integer,String> msg;
    static {
        msg=new LinkedHashMap<>();
        msg.put(1,"一等奖");
        msg.put(2,"二等奖");
        msg.put(3,"三等奖");
        msg.put(4,"四等奖");
        msg.put(5,"五等奖");
        msg.put(6,"六等奖");
    }
    private LuckDao dao;
    public LuckServiceImpl(){
        dao=new LuckDaoImpl();

    }

    @Override
    public R add(int uid) {
        //校验
        if(uid>0){
            //校验用户能否抽奖
            Luck luck=dao.selectByUid(uid);
            if(luck!=null){
                if(checkToday(luck.getCtime())){
                    //今日已抽奖
                   return R.fail();
                }
            }
            luck=new Luck();
            luck.setUid(uid);
            Random random=new Random();
            luck.setLevel(random.nextInt(6)+1);
            luck.setLmsg(msg.get(luck.getLevel()));
            luck.setInfo("恭喜中奖");
            if(dao.luckadd(luck)>0){
                // 抽奖
               return R.ok(luck);
            }else {
                return R.fail();
            }
        }
        return R.fail();
    }

    @Override
    public R all(int uid) {
        return R.ok(dao.selectByUids(uid));
    }

    private boolean checkToday(Date date){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date).equals(sdf.format(new Date()));
    }
}
